#!/bin/bash

prog="system-prepare:";
configopts="";

if test "x$1" == "x"; then
   echo "fuck";
   exit 5;
fi

# get the arguments
while test "x$*" != "x"; do
   opt="$1";
# all command line arguments one to the left
   shift;
# switch arguments
   case $opt in
      -pl=* | --platform=*)
         platform="`echo $opt | cut -f 2- -d '='`";
         case $platform in
            unix)
               configopts="$configopts CC=gcc";
               ;;
            avr-*)
               mcu="`echo $platform | cut -f 2- -d '-'`";
               configopts="$configopts --build=`./config.guess` --host=avr";
               configopts="$configopts mcu=$mcu";
               configopts="$configopts CC=avr-gcc CFLAGS=";
               ;;
            *)
               echo "$prog error: unknown platform \`$platform\`";
               exit 5;
               ;;
         esac
         ;;
      -h | --help)
         echo "$prog no help available :P";
         exit 0;
         ;;
      *)
      echo "$prog error: unknown argument \`$opt\`";
      exit 5;
      ;;
   esac
done;

echo "$prog preparing for \`$platform\`";

# create build directory if not exist
if test ! -d build ; then
   echo "$prog creating \`./build\` dir";
   mkdir build
fi

builddir=build/$platform;

# create build/platform directory if not exist
if test ! -d build/$platform ; then
   echo "$prog creating \`./$builddir\` dir";
   mkdir $builddir
fi

# add srcdir to configure options
configopts="$configopts --srcdir=../..";

# add sub directory
touch build/.subdirs
grep $platform build/.subdirs || echo $platform >> build/.subdirs;

# create build/Makefile if not exist
if test ! -f build/Makefile ; then
   echo "$prog creating Makefile in \`./build\` dir";
   cat <<EOF > build/Makefile
DIRS=\$(shell cat .subdirs)

# required for 'make' without explicit target to work
all:
	for dir in \$(DIRS) ; do \\
		make -C \$\$dir \$@ || exit 5; \\
	done;

.DEFAULT:
	for dir in \$(DIRS) ; do \\
		make -C \$\$dir \$@ || exit 5; \\
	done;
EOF
fi

srcdir=`pwd`;
cd $builddir
echo "$prog calling configure with options: $configopts";
$srcdir/configure $configopts

exitCode=${PIPESTATUS[0]}
if test "x$exitCode" != "x0"; then
   echo "$prog exit from \`$builddir\` with exit code \`$exitCode\`";
else
   echo "$prog `date` done: \`$builddir\`";
fi
exit $exitCode;


